<?php

define('N', "\n");
define('eregEMAIL', "/[0-9a-z_]+@[0-9a-z_^\.\-]+\.[a-z]{2,3}/i");
define('eregUSERNAME', "/[0-9a-z_\.\-]+/i");
define('eregPHONE', "/\+?[0-9\s\(\)\-\.]{5,30}/i");

function _val($arr, $val)
{
  if (isset($arr[$val]))
    return $arr[$val];
  else
    return false;
}

function _str($arr, $val)
{
  if (isset($arr[$val]))
    return $arr[$val];
  else
    return "";
}

function __str($arr, $val)
{
  return htmlspecialchars(_str($arr, $val));
}

function _p($val)
{
  return __str($_POST, $val);
}

function _txt($str, $replacementArr=array())
{
  $search = array();
  $replace = array();

  foreach ($replacementArr as $key=>$value)
  {
    $search[count($search)] = $key;
    $replace[count($replace)] = $value;
  }
  return str_replace($search, $replace, $str);
}

function sanitize($text)
{
  return str_replace(N, "<br />", htmlspecialchars($text));
}

function error($str){return array("message" => "$str", "type" => "error");}
function message($str){return array("message" => "$str", "type" => "message");}
function message_to_html($messages)
{
  $result = '';
  if( isset($messages) )
    foreach($messages as $message)
      switch ($message['type']) {
        case 'error':
          $result .= "<div class='red'>{$message['message']}</div>";
        break;
        default:
          $result .= "<div class='green'>{$message['message']}</div>";
      }
  return $result;
}
function page404($str = "Ошибка: страница не найдена на сервере"){
  global $template;
  $template = 'main';
  echo message_to_html(array(error($str)));
}

function quote_smart($value)
{
  if( get_magic_quotes_gpc() ) $value = stripslashes($value);
  if( !is_numeric($value) ) $value = "'" . mysql_real_escape_string($value) . "'";

  return $value;
}

$tr = array(
 "Ґ"=>"G","Ё"=>"YO","Є"=>"E","Ї"=>"YI","І"=>"I",
 "і"=>"i","ґ"=>"g","ё"=>"yo","№"=>"#","є"=>"e",
 "ї"=>"yi","А"=>"A","Б"=>"B","В"=>"V","Г"=>"G",
 "Д"=>"D","Е"=>"E","Ж"=>"ZH","З"=>"Z","И"=>"I",
 "Й"=>"Y","К"=>"K","Л"=>"L","М"=>"M","Н"=>"N",
 "О"=>"O","П"=>"P","Р"=>"R","С"=>"S","Т"=>"T",
 "У"=>"U","Ф"=>"F","Х"=>"H","Ц"=>"TS","Ч"=>"CH",
 "Ш"=>"SH","Щ"=>"SCH","Ъ"=>"'","Ы"=>"YI","Ь"=>"",
 "Э"=>"E","Ю"=>"YU","Я"=>"YA","а"=>"a","б"=>"b",
 "в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"zh",
 "з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l",
 "м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
 "с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
 "ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"'",
 "ы"=>"yi","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya"
);

function translit($cyr_str) {
 global $tr;
 return strtr($cyr_str, $tr);
}

function proceed_textual( $numeric, $many, $one, $two, $with_num = true )
{
  $numeric = (int) abs($numeric);
  
  $d10 = $numeric%10; 
  $d100 = $numeric%100;
  
  if ( ($d10 == 1) && ($d100 != 11) ) $how = $one;
  elseif( (1<$d10) && ($d10<5) && ($d100<5 || $d100>21 ) ) $how = $two;
  else $how = $many;
  
  return $with_num ? (int)$numeric." ".$how : $how;
}

function send_email($toName, $toEmail, $subject, $message, $from = "")
{
  if (!$from) $from = $_SERVER["HTTP_HOST"]." <webmaster@".$_SERVER["HTTP_HOST"].">";
  $headers  = 'MIME-Version: 1.0' . "\r\n";
  $headers .= 'Content-type: text/plain; charset=utf-8' . "\r\n";
  $headers .= "To: <".$toEmail.">" . "\r\n";
  $headers .= "From: ".$from."\r\n";
  $headers .= "Message-ID: <".time()." TheSystem@".$_SERVER['SERVER_NAME'].">"."\r\n";
  $headers .= "X-Mailer: PHP v".phpversion()."\r\n";           // These two to help avoid spam-filters

  $res = mail($toEmail, $subject, $message, $headers);

  return $res;
}

function mb_str_replace($needle, $replacement, $haystack)
{
  $needle_len = mb_strlen($needle, "utf-8");
  $replacement_len = mb_strlen($replacement, "utf-8");
  $pos = mb_strpos($haystack, $needle, 0, "utf-8");
  while ($pos !== false)
  {
      $haystack = mb_substr($haystack, 0, $pos, "utf-8") . $replacement
              . mb_substr($haystack, $pos + $needle_len, "utf-8");
      $pos = mb_strpos($haystack, $needle, $pos + $replacement_len, "utf-8");
  }
  return $haystack;
}

function normalize($s) {
  $s = mb_convert_case(trim($s), MB_CASE_LOWER, "utf-8");
  while (mb_strpos($s, "ё") !== FALSE) $s = mb_ereg_replace("ё", "е", $s);
  while (mb_strpos($s, "  ") !== FALSE) $s = mb_ereg_replace("  ", " ", $s);
  return $s;
}

function get_extention($file)
{
  return strtolower(substr($file, strrpos($file,'.')+1));
}

function get_name($file)
{
  return strtolower(substr($file, 0, strrpos($file,'.')));
}

function create_path($path_to_create)
{
  $path="";
  $fullpath=explode('/',$path_to_create);
  foreach($fullpath as $dir){
    $path.=$dir."/";
    if(!is_dir($path)) mkdir($path,0777);
  }
}

function options($a,$selected=false)
{
  $result = "";
  if( $selected === false ) $selected = key($a);
  if( !is_array($selected) ) $selected = array($selected);

  foreach($a as $key=>$value){
    $s = in_array($key, $selected) ? "selected" : "";
    $result .= "<option $s value='".$key."'>$value</option>";
  }
  return $result;
}

function parseSearchQuery($query, $likeField)
{
  $query = trim(preg_replace('| +|', ' ', $query));
  $keywords = preg_split("/[\s\,\.]+/", $query);
  foreach($keywords as $keyword) $likes[] = $likeField." LIKE '%".$keyword."%'";
  $res = empty($likes) ? '' : implode(" OR ", $likes);
  return $res;
}

function cutText($str)
{
  return mb_substr(strip_tags($str), 0, 400, 'utf-8');
}

function redirect($url)
{
   if (!headers_sent())
		header('Location: '.$url);
   else
   {
		echo '<script type="text/javascript">';
    	echo 'window.location.href="'.$url.'";';
       	echo '</script>';
       	echo '<noscript>';
       	echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
       	echo '</noscript>';
   }
}

$ru_months = array("января","февраля","марта","апреля","мая","июня","июля","августа","сентября","октября","ноября","декабря");

function ru_date($date,$time=true,$del=", ")
{
  global $ru_months;
  $date = strtotime($date);
  return date("j ".($ru_months[date("m",$date)-1])." Y".($time?$del."G:i":""),$date);
}

function js_tag()
{
  $r = '';
  $tags = func_get_args();
  foreach ($tags as $tag)
    $r .= '<script type="text/javascript" src="/js/'.$tag.'.js"></script>';
  return $r;
}

function a()
{
  return func_get_args();
}

function XMail( $from, $to, $subj, $text, $files)
// $files = a ( a (name, tmp_name, size, etc) , . . .   )
{
  $un        = strtoupper(uniqid(time()));
  $head      = "From: $from\n";
  $head     .= "To: $to\n";
  $head     .= "Subject: $subj\n";
  $head     .= "X-Mailer: PHPMail Tool\n";
  $head     .= "Reply-To: $from\n";
  $head     .= "Mime-Version: 1.0\n";
  $head     .= "Content-Type:multipart/mixed;";
  $head     .= "boundary=\"----------".$un."\"\n\n";
  $zag       = "------------".$un."\nContent-Type:text/html; charset=utf-8\n";
  $zag      .= "Content-Transfer-Encoding: 8bit\n\n$text\n\n";
  
  foreach ($files as $file) {
    if(isset($file['size'])&&($file['size']>0)){
      $f         = fopen($file['tmp_name'],"rb");
      $zag      .= "------------".$un."\n";
      $zag      .= "Content-Type: application/octet-stream;";
      $zag      .= "name=\"".translit($file['name'])."\"\n";
      $zag      .= "Content-Transfer-Encoding:base64\n";
      $zag      .= "Content-Disposition:attachment;";
      $zag      .= "filename=\"".translit($file['name'])."\"\n\n";
      $zag      .= chunk_split(base64_encode(fread($f,filesize($file['tmp_name']))))."\n";
    }
  }
  
  if (!@mail("$to", "$subj", $zag, $head))
    return 0;
  else
    return 1;
}